<template>
  <div>
    <h1>{{id ? '修改' : '新建'}}广告位</h1>
    <el-form label-width="100px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="广告">
        <el-row :gutter="16" type="flex" style="flex-wrap:wrap;">
          <el-col :span="8" v-for="(item, index) in model.items" :key="index">
            <div class="colStyle">
              <el-form-item label="图片">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="getAuthHeaders()"
                  :show-file-list="false"
                  :on-success="res => $set(item, 'img', res.url)"
                >
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="跳转地址">
                <el-input v-model="item.url"></el-input>
              </el-form-item>
              <el-button class="middle" type="danger" icon="el-icon-delete" circle @click="model.items.splice(index, 1)"></el-button>
            </div>
          </el-col>
        </el-row>
        <el-button type="primary" round class="middle" @click="model.items.push({})"><i class="el-icon-plus"></i> 添加广告</el-button>
      </el-form-item>
      <el-form-item style="margin-top:1rem">
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: String
  },
  data () {
    return {
      model: {
        items: []
      }
    }
  },
  methods: {
    async save () {
      if (this.model.name.trim() === '') {
        this.$message.error('请输入广告名称')
        return
      }
      if (this.id) {
        await this.$http.put(`/rest/ads/${this.id}`, this.model)
        this.$message.success('修改成功')
      } else {
        await this.$http.post('/rest/ads', this.model)
        this.$message.success('保存成功')
      }
      this.$router.push('/ads/list')
    },
    async getName () {
      const { data: res } = await this.$http.get(`/rest/ads/${this.id}`)
      this.model = Object.assign({}, this.model, res)
    }
  },
  created () {
    this.id && this.getName()
  }
}
</script>

<style scoped>
.middle {
  display: block;
  margin: 0 auto;
  margin-top: 1rem;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 5rem;
  height: 5rem;
  line-height: 5rem;
  text-align: center;
}
.avatar {
  width: 10rem;
  max-height: 10rem;
  display: block;
}
.el-rate {
  margin-top: 0.6rem;
}
.el-col {
    margin-bottom: 1rem;
}
.colStyle {
  background:#f2f6fc;
  border-radius: 1rem;
  padding: 1rem;
}
</style>
